from django.shortcuts import render,redirect,reverse
from django.shortcuts import render_to_response
from . models import User
# from celery_tasks.tasks import send_redis_active_email
from django.conf import settings
from django.http import HttpResponse,JsonResponse
from django.core.mail import send_mail
from django.views.generic import View
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.contrib.auth import authenticate,login
from captcha.fields import CaptchaStore
from captcha.helpers import captcha_image_url
from django.core.cache import cache
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.client import CommonRequest
from .form import UserForm
# from / import phone
from .phone import send_sms,get_code

from utils import *
from . import restful
import re
import json




def index(request):
    register_form = UserForm()
    return render(request,'login.html',{'register_form':register_form})

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        allow = request.POST.get('allow')
        if not all([username,password,email,allow]):
            return render(request,'register.html',{'errmsg':'请填写完整'})

        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return render(request,'register.html',{'errmsg':'邮件格式错误'})

        if allow != allow:
            return render(request,'register.html',{'errmsg':'请同意协议'})
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = None
        if user:
            return render(request,'register.html',{'errmsg':'用户名已存在'})
        user = User.objects.create_user(username,password,email)
        user.is_active = 0
        user.save()

        # 加密
        serializer = Serializer(settings.SECRET_KEY,3600)
        info = {'confirm':user.id}
        token = serializer.dumps(info).decode()
        # # 发邮件
        subject = '天天生鲜'
        message = ''
        sender = settings.EMAIL_FROM
        receiver = [email]
        html_message = '<h1>%s,欢迎使用天天生鲜,您已成为我们的用户</h1>请点击下面的链接激活用户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' \
                       % (username, token, token)
        send_mail(subject, message, sender, receiver, html_message=html_message)
        # send_redis_active_email.delay(email,username,token)
        return redirect(reverse('index'))

class ActiveView(View):
    def get(self,request,token):
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            info = serializer.loads(token)
            user_id = info['confirm']
            user = User.objects.get(id=user_id)
            user.is_active = 1
            user.save()
            return redirect(reverse('index'))
        except SignatureExpired as  e :
            return HttpResponse('激活连接已过期')

class LoginView(View):
    def get(self,request):
        if 'username' not in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = 'checked'
        else:
            username = ''
            checked = ''
        hashkey=CaptchaStore.generate_key()
        image_url= captcha_image_url(hashkey)
        res = UserForm()
        return render(request,'login.html',locals())

    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')

        if not([username,password]):
            return render(request,'login.html',{'errmsg':'数据不完整'})
        user = authenticate(username=username,password=password)
        if user is not None:
            if user.is_active:
                login(request,user)
                # 判断是否记住用户
                response =  redirect(reverse('index'))
                remember = request.POST.get('remember')

                if remember =='on':
                    response.set_cookie('username',username,max_age=7*24*3600)
                else:
                    response.delete_cookie('username')

                return HttpResponse()


            else:
                return render(request,'login.html',{'errmsg':'账户未激活'})

        else:
            return render(request,'index.html',{'errmsg':'用户名密码正确'})



def get_username(request,username):
    data = {
        'erro': 0,
        'pandan': True
    }
    try:
        user = User.objects.get(username = username)
    except User.DoesNotExist:
        data['erro'] = username
        data['pandan'] = False
        return HttpResponse(json.dumps(data))
    return HttpResponse(json.dumps(data))

# def page_not_found(request,exception):
#     return render(request,'404.html')
#
# def page_error(request):
#     return render(render,'500.html')
#
def img_refresh(request):
    if not request.is_ajax():
        return HttpResponse('不是ajax请求')
    new_key = CaptchaStore.generate_key()
    to_json_response = {
        'hashkey':new_key,
        'image_url':captcha_image_url(new_key),

    }
    return HttpResponse(json.dumps(to_json_response))

def img_check(request):
    print('验证中...')
    if request.is_ajax():
        cs = CaptchaStore.objects.filter(response=request.GET.get('code'),
                                         hashkey=request.GET.get('hashkey'))
        print(cs)
        if cs:
            json_data = {'status':1}
        else:
            json_data = {'status':0}
        return JsonResponse(json_data)
    else:
        json_data = {'status':0}
        return JsonResponse(json_data)


#测试成功
# def test_redis(request):
# # #     cache.set('name','tom',20)
# # #     print(cache.has_key('name'))
# # #     print(cache.get('name'))
# # #     return HttpResponse('redis')

# def send_sms(phone,code):
#     client = AcsClient('LTAIwcVRm7iZ7pIg','KQ4AgwtaJQPTjLJEQ1X6ltVNHNLcli','cn-hangzhou')
#     code = '{"code":%s}'%(code)
#     request = CommonRequest()
#     request.set_accept_format('json')
#     request.set_domain('dysmsapi.aliyuncs.com')
#     request.set_method('POST')
#     request.set_protpcol_type('https')
#     request.set_version('2019-08-13')
#     request.set_action_name('sendSms')
#
#     request.add_query_param('RegionId','cn-hangzhou')
#     request.add_query_param('PhoneNumbers',phone)
#     request.add_query_param('SignName','')
#     request.add_query_param('TemplateCode','')
#     request.add_query_param('TemplateParam',code)
#
#     response = client.do_action(request)
#
#     print(str(response,encoding='utf-8'))
#
#     return str(response,encoding='ut-8')
#
# def get_code(n=6,alpha=True):
#     s= ''
#     for i in range(n):
#         num = random.randint(0,9)
#         if alpha:
#             upper_alpha = chr(random.randint(65,90))
#             lower_alpha = chr(random.randint(97,122))
#             num = random.choice([num,upper_alpha,lower_alpha])
#         s = s+str(num)
#     return s
# if __name__ =='__main__':
#     send_sms('15703470625',get_code(6,False))
#     print(get_code(6,False))
#     print(get_code(6,True))
#
# 发短信接口
def sms_send(request):
    phone = request.GET.get('phone')
    code = get_code(6,False)
    cache.set(phone,code,60)
    print('判断缓存中是否有',cache.has_key(phone))
    print('获取redis验证码',cache.get(phone))
    result = send_sms(phone,code)
    return HttpResponse(result)
# 短信验证码校验
def sms_check(request):
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    print('缓存中是否有:',cache.has_key(phone))
    print('取值'),cache.get(phone)
    cache_code = cache.get(phone)
    if code == cache_code:
        return restful.ok('ok',data=None)
    else:
        return restful.params_error('验证码错误',data=None)
#
#
